package org.ccay.manage.sitemap.service.impl;

import static org.ccay.core.util.DaoUtil.assertEffected;

import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.ccay.core.base.BatchVO;
import org.ccay.core.base.PageVO;
import org.ccay.core.base.PagedResult;
import org.ccay.core.exception.ApplicationException;
import org.ccay.core.ioc.ISelfInject;
import org.ccay.core.log.CcayLoggerFactory;
import org.ccay.core.log.ILogger;
import org.ccay.core.request.impl.RequestContext;
import org.ccay.core.validator.Validate;
import org.ccay.manage.sitemap.dao.ISiteMapManageDao;
import org.ccay.manage.sitemap.service.ISiteMapManageService;
import org.ccay.sitemap.SiteMapApplicationException;
import org.ccay.sitemap.SiteNodeSimpleVO;
import org.ccay.sitemap.SiteNodeVO;
import org.ccay.sitemap.dao.ISiteMapQueryDao;
import org.ccay.sitemap.service.ISiteMapQueryService;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * siteMap 管理服务类
 */
@Named
public class SiteMapManageService implements ISiteMapManageService,ISelfInject {

	/**
	 * 创建名字已经存在的节点
	 */
	private static final String EX_NAME_EXISTS_CREATE = "ccay.sitemap.00010001";

	/**
	 * 更新为已经存在的名字
	 */
	private static final String EX_NAME_EXISTS_MODIFY = "ccay.sitemap.00010002";

	/**
	 * 已经存在子，不能删除
	 */
	private static final String EX_CHILDREN_EXISTS = "ccay.sitemap.00010003";
	
	private static final ILogger logger = CcayLoggerFactory.getLogger(SiteMapManageService.class); 

	private ISiteMapManageService self;
	
	@Inject 
	private ISiteMapQueryService query;
	
	@Inject
	private ISiteMapQueryDao siteMapQueryDao;
	
	@Inject
	private ISiteMapManageDao siteMapManageDao;

	public void setSelf(Object self) {
		this.self = (ISiteMapManageService)self;
	}
	
	/* (non-Javadoc)
	 * @see org.ccay.sitemap.service.ISiteMapService#createSiteNode(org.ccay.sitemap.SiteNodeVO)
	 */
	@CacheEvict(value = ISiteMapQueryService.SITE_MAP, allEntries = true)
	@Validate
//	@Audit(module="SiteMap Management",operation="create siteNode",message="create siteNode name is {#newSiteNode.name}")
//	@DifAudit(objectId="#siteNodeId",subject=0)
	public void createSiteNode(SiteNodeVO newSiteNode)
			throws ApplicationException {
		if (siteMapManageDao.findExistsNodeCount(newSiteNode) > 0) {
			throw new SiteMapApplicationException(EX_NAME_EXISTS_CREATE);
		}
		assertEffected(siteMapManageDao.createSiteNode(newSiteNode), ISiteMapQueryService.SITE_MAP_NODE);
	}

	@CacheEvict(value = ISiteMapQueryService.SITE_MAP, allEntries = true)
	@Validate
//	@Audit(module="SiteMap Management",operation="update siteNode")
//	@DifAudit(objectId="#siteNodeId",subject=0)
	public void updateSiteNode(SiteNodeVO existedNode)
			throws ApplicationException {
		
		if(existedNode.getParent() == null){
			SiteNodeVO node = new SiteNodeVO();
			node.setSiteNodeId(0);
			existedNode.setParent(node);			
		}
		assertEffected(siteMapManageDao.updateSiteNode(existedNode), ISiteMapQueryService.SITE_MAP_NODE);
		// 更新其对应的视图

		// 放在这里只为验证事务回滚
		if (siteMapManageDao.findExistsNodeCount4Update(existedNode) >= 1) {
			throw new SiteMapApplicationException(EX_NAME_EXISTS_MODIFY);
		}
	}

	@CacheEvict(value = ISiteMapQueryService.SITE_MAP, allEntries = true)
//	@CcayOperation(code = RequestConstants.UPDATE, desc = RequestConstants.UPDATE_DESC)
	@Validate
//	@Audit(module="SiteMap Management",operation="update siteNode",message="batch update siteNode")
	public void updateSiteNodeList(List<SiteNodeVO> existedNodes)
			throws ApplicationException {
		siteMapManageDao.updateSiteNodeList(existedNodes);
	}

	@CacheEvict(value = ISiteMapQueryService.SITE_MAP, allEntries = true)
//	@Audit(module="SiteMap Management",operation="delete siteNode",message="batch delete siteNode")
	public void deleteSiteNodeList(List<SiteNodeVO> siteNodeVOs)
			throws ApplicationException {
		//先校验是否存在子节点，如果存在子节点则不允许删除
		int count=siteMapManageDao.checkSiteNodeList(siteNodeVOs);
		if (count > 0) {
			// 无法完全删除，可能是存在子节点
			throw new SiteMapApplicationException(EX_CHILDREN_EXISTS);
		}
		siteMapManageDao.deleteSiteNodeList(siteNodeVOs);
	}

	@CacheEvict(value = ISiteMapQueryService.SITE_MAP, allEntries = true)
//	@Audit(module="SiteMap Management",operation="delete siteNode",message="delete siteNode name is {#siteNodeVO.name}")
	public void deleteSiteNode(SiteNodeVO siteNodeVO)
			throws ApplicationException {
		if (siteMapManageDao.deleteSiteNode(siteNodeVO) <= 0) {
			// 无法删除，可能是存在子节点
			throw new SiteMapApplicationException(EX_CHILDREN_EXISTS);
		}
	}

	/**
	 * 栏目批量导入
	 */
	@Validate
//	@CcayOperation(code = RequestConstants.IMPORT, desc = RequestConstants.IMPORT_DESC)
//	@Audit(module="SiteNode  Management",operation="Import SiteNode ",message="import siteNode  successfully")
	@CacheEvict(value = ISiteMapQueryService.SITE_MAP, allEntries = true)
	public void importSiteNode(List<SiteNodeVO> siteNodeList) throws ApplicationException {
		siteMapManageDao.importSiteNode(siteNodeList);
	}
	
	/**
	 * listSiteMap页面导出
	 */
//	@CcayOperation(code = RequestConstants.EXPORT, desc = RequestConstants.EXPORT_DESC)
//	@Audit(module="SiteNode  Management",operation="Export SiteNode ",message="export siteNode  successfully")
	public void exportClassifyByIExcel(SiteNodeVO querySiteNode) throws ApplicationException{
//		localExcelExportAssistant.submitExportTask("ccay.sitemap.siteNode", querySiteNode);
	}

//	@CcayOperation(policy=SecurityPolicy.AllSystemUser)
	public List<SiteNodeVO> findAllSiteNodes(SiteNodeVO siteNodeVO) throws ApplicationException{
		return siteMapQueryDao.findSiteNodeList(siteNodeVO);
	}
	
	@CacheEvict(value = ISiteMapQueryService.SITE_MAP, allEntries = true)
	@Validate
//	@Audit(module="SiteMap Management",operation="create siteNode",message="batch create siteNode")
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public void createSiteNodeList(List<SiteNodeVO> siteNodeVO)
			throws ApplicationException {
		siteMapManageDao.createSiteNodeList(siteNodeVO);
	}
	
	public void batchOperation(BatchVO<SiteNodeVO> batchItems)throws ApplicationException {
		// 如果对象不为空 执行
		if (!batchItems.getItems2Delete().isEmpty()) {
			self.deleteSiteNodeList(batchItems.getItems2Delete());
		}
		// 如果对象不为空 执行
		if (!batchItems.getItems2Update().isEmpty()) {
			self.updateSiteNodeList(batchItems.getItems2Update());
		}
		// 如果对象不为空 执行
		if (!batchItems.getItems2Create().isEmpty()) {
			self.createSiteNodeList(batchItems.getItems2Create());
		}
	}

	public PagedResult<SiteNodeVO> findPageSiteNodeList(
			SiteNodeVO siteNode, PageVO pageVO)
			throws ApplicationException {
		try{
			return siteMapQueryDao.findPagedSiteNodeList(siteNode, pageVO);
		}catch(Exception e){
			throw new SiteMapApplicationException("ccay.sitemap.00010007",e);
		}
	}
	@Override
	public SiteNodeVO findSiteNode(SiteNodeVO siteNodeVO) throws ApplicationException{
		return query.findSiteNode(siteNodeVO);
	}

	public SiteNodeVO findWholeSiteMap()
			throws ApplicationException {
		 return query.findWholeSiteMap(RequestContext.getCurrent().getUserLanguage());		 
	}
	
	public SiteNodeVO findWholeSiteMap(String language)
			throws ApplicationException {
		return query.findWholeSiteMap(language);
	}
	
	public SiteNodeVO findOneSiteMap(String parentId) throws ApplicationException {
		return query.findOneSiteMapByParentId(parentId);
	}

	public SiteNodeSimpleVO findAuthorizedSiteMap() throws ApplicationException {
		return query.findAuthorizedSiteMap();
	}
	
	public int findCountSiteNode(SiteNodeVO siteNodeVO){
		return query.findCountSiteNode(siteNodeVO);
	}
	
	public List<SiteNodeVO> findSiteNodeTreeList(SiteNodeVO siteNodeVO)
			throws ApplicationException {
		return query.findSiteNodeTreeList(siteNodeVO);
	}
	
}